package org.siqisource.webstart.core.utils.converter;

import java.lang.reflect.Field;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

import org.siqisource.webstart.core.utils.model.Model;
import org.siqisource.webstart.core.utils.model.Property;

public class ModelConverter {

	public static Model modelToTable(Class<?> clazz) {
		Model model = new Model();
		model.setTable(getTableName(clazz));
		for (Field field : clazz.getDeclaredFields()) {

			Property property = new Property();
			property.setId(field.isAnnotationPresent(Id.class));
			if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(Column.class)) {
				property.setColumn(NameConverter.propertyToColumn(field.getName()));
			}
			property.setName(field.getName());
			model.addProperty(property);
		}

		return model;
	}

	public static String getTableName(Class<?> clazz) {
		Table table = (Table) clazz.getAnnotation(Table.class);
		if (table != null) {
			return table.name();
		} else {
			return NameConverter.propertyToColumn(clazz.getSimpleName());
		}
	}

}
